<?php
/**
 * Created by PhpStorm.
 * User: zhuanggit
 * Date: 2019/2/28
 * Time: 14:53
 */
namespace App\Observers;

use App\Models\Member;
use App\Models\Program;
use Illuminate\Support\Facades\DB;

class ProgramObserver
{
    public function updated(Program $program)
    {
        //条件判断绩效表中是否有不在项目参与人中的信息，有就删除
        DB::table('grades')->where('program_id',$program->id)->whereNotIn('member_id', $program->members)->delete();
        if($program->ratioxy!=null&&$program->ratiogm!=null&&$program->ratiowd!==null){
            //设置进度为C
            DB::table('programs')->where('id', $program->id)->update(['plan'=>'C']);
            DB::table('grades')->where('program_id', $program->id)->update(['plan'=>1]);
        }else{
            DB::table('programs')->where('id', $program->id)->update(['plan'=>'A']);
        }
        if($program->state==1){
            DB::table('programs')->where('id', $program->id)->update(['plan'=>'D']);
        }
    }
    public function deleted(Program $program){
        //删除项目连表删除绩效表的数据
        DB::table('grades')->where('program_id',$program->id)->delete();
        DB::table('tasks')->where('program_id',$program->id)->delete();
    }
    public function created(Program $program){
        $member=Member::all()->toArray();
        foreach ($program->members as $val) {
            //查找数据表中是否有记录，有就更新，没有就新增
            foreach ($member as $item) {
                if ($val == $item['id']) {
                    DB::table('tasks')
                        ->updateOrInsert(
                            ['program_id' => $program->id, 'member_id' => $val],
                            [
                                'program_id' => $program->id,
                                'member_id' => $val,
                                'branch_id' => $item['branch_id']
                            ]
                        );
                    DB::table('grades')
                        ->updateOrInsert(
                            ['program_id' => $program->id, 'member_id' => $val],
                            ['program_id' => $program->id, 'time' => $program->time, 'member_id' => $val,'branch_id'=>$item['branch_id']]
                        );
                }
            }
        }
    }
}
